<script setup>
import { ref, onMounted } from 'vue';
import { ElNotification, ElLoading, ElDialog } from 'element-plus';
import { Search, Star } from '@element-plus/icons-vue';
import { Click, FeedBack, SearchAds } from "@/api/index.js";
import SvgIcon from "@/components/iconfont/SvgIcon.vue";

const ads = ref([]);
const topAds = ref([]);
const hobbyTag = ref('');
const province = ref('');
const city = ref('');
const selectedAd = ref(null);
const creativeDialogVisible = ref(false); // 控制创意详情框的显示
const currentCreativeIndex = ref(0); // 当前显示的创意索引
const feedbackDialogVisible = ref(false); // 控制反馈对话框的显示
const feedbackForm = ref({ unit_id: null, feedback: 'like', comment: '' });

// 记录广告点击
const recordClick = async (adId) => {
  try {
    await Click({ unit_id: adId });
    // 更新点击量
    const ad = topAds.value.find((ad) => ad.id === adId) || ads.value.find((ad) => ad.id === adId);
    if (ad) ad.click_count += 1;
  } catch (error) {
    console.error('Failed to record click:', error);
    ElNotification({ title: 'Error', message: 'Failed to record click', type: 'error' });
  }
};

// 检索广告
const searchAds = async () => {
  const loading = ElLoading.service({ fullscreen: true, text: '加载中...' });
  try {
    const response = await SearchAds({ hobby_tag: hobbyTag.value, province: province.value, city: city.value } );
    ads.value = response;
  } catch (error) {
    console.error('Failed to fetch ads:', error);
    ElNotification({ title: 'Error', message: 'Failed to fetch ads', type: 'error' });
  } finally {
    loading.close();
  }
};

// 获取热门广告
const fetchTopAds = async () => {
  const loading = ElLoading.service({ fullscreen: true, text: '加载中...' });
  try {
    const response = await SearchAds({limit:3});
    topAds.value = response;
  } catch (error) {
    console.error('Failed to fetch top ads:', error);
    ElNotification({ title: 'Error', message: 'Failed to fetch top ads', type: 'error' });
  } finally {
    loading.close();
  }
};

// 提交用户反馈
const submitFeedback = async () => {
  try {
    await FeedBack(feedbackForm.value);
    ElNotification({ title: 'Success', message: 'Feedback submitted successfully!', type: 'success' });
    closeFeedbackDialog();
  } catch (error) {
    console.error('Failed to submit feedback:', error);
    ElNotification({ title: 'Error', message: 'Failed to submit feedback', type: 'error' });
  }
};

// 打开反馈对话框
const openFeedbackDialog = () => {
  if (selectedAd.value) {
    feedbackForm.value.unit_id = selectedAd.value.id;
  }
  feedbackDialogVisible.value = true;
};

// 关闭反馈对话框
const closeFeedbackDialog = () => {
  feedbackDialogVisible.value = false;
  resetFeedback();
};

// 重置反馈表单
const resetFeedback = () => {
  feedbackForm.value = { unit_id: null, feedback: 'like', comment: '' };
};

// 拼接完整 URL
const getFullUrl = (url) => {
  return url?.startsWith('http') ? url : `http://116.62.230.206:8888/${url}`;
};

// 打开创意详情框
const openCreativeDialog = (ad) => {
  selectedAd.value = ad;
  currentCreativeIndex.value = 0; // 重置为第一个创意
  creativeDialogVisible.value = true;
  recordClick(ad.id); // 记录点击
};

// 切换创意
const switchCreative = (index) => {
  currentCreativeIndex.value = index;
};

// 初始化加载热门广告
onMounted(() => {
  fetchTopAds();
});
</script>

<template>
  <div class="ad-display-container">
    <!-- 热门广告轮播 -->
    <el-carousel height="300px" :interval="5000" type="card">
      <el-carousel-item v-for="ad in topAds" :key="ad.id">
        <el-card class="top-ad-card">
          <h3>{{ ad.name }}</h3>
          <div v-if="ad.creatives?.length">
            <!-- 主创意预览 -->
            <el-image
                v-if="ad.creatives[0].creative_type === '图片'"
                :src="getFullUrl(ad.creatives[0].url)"
                fit="cover"
                style="width: 100%; max-height: 150px;"
            />
            <video
                v-if="ad.creatives[0].creative_type === '视频'"
                :src="getFullUrl(ad.creatives[0].url)"
                controls
                style="width: 100%; max-height: 150px;"
            />
          </div>
          <div class="ad-stats">
            <!-- 点击量 -->
            <div class="stat-item">
              <el-icon><SvgIcon iconName="icon-dianji" /></el-icon>
              <span>{{ ad.click_count }}</span>
            </div>
            <!-- 点赞量 -->
            <div class="stat-item">
              <el-icon><SvgIcon iconName="icon-xihuan" /></el-icon>
              <span>{{ ad.like_count }}</span>
            </div>
            <div class="stat-item">
              <el-icon><SvgIcon iconName="icon-buxihuan" /></el-icon>
              <span>{{ ad.dislike_count }}</span>
            </div>
          </div>
          <el-button type="primary" @click="openCreativeDialog(ad)" class="detail-button">
            详情
          </el-button>
        </el-card>
      </el-carousel-item>
    </el-carousel>

    <!-- 广告检索 -->
    <div class="search-bar">
      <el-input
          v-model="hobbyTag"
          placeholder="输入兴趣标签"
          style="width: 200px; margin-right: 10px;"
      />
      <el-input
          v-model="province"
          placeholder="输入省份"
          style="width: 150px; margin-right: 10px;"
      />
      <el-input
          v-model="city"
          placeholder="输入城市"
          style="width: 150px; margin-right: 10px;"
      />
      <el-button type="primary" @click="searchAds">
        <el-icon><Search /></el-icon> 检索
      </el-button>
    </div>

    <!-- 广告列表 -->
    <div class="ads-list">
      <el-card v-for="ad in ads" :key="ad.id" class="ad-card">
        <h3>{{ ad.name }}</h3>
        <div class="ad-preview">
          <div v-if="ad.creatives?.length">
            <el-image
                v-if="ad.creatives[0].creative_type === '图片'"
                :src="getFullUrl(ad.creatives[0].url)"
                fit="cover"
                style="width: 100%; max-height: 150px;"
            />
            <video
                v-if="ad.creatives[0].creative_type === '视频'"
                :src="getFullUrl(ad.creatives[0].url)"
                controls
                style="width: 100%; max-height: 150px;"
            />
          </div>
          <div class="ad-stats">
            <!-- 点击量 -->
            <div class="stat-item">
              <el-icon><SvgIcon iconName="icon-dianji" /></el-icon>
              <span>{{ ad.click_count }}</span>
            </div>
            <!-- 点赞量 -->
            <div class="stat-item">
              <el-icon><SvgIcon iconName="icon-xihuan" /></el-icon>
              <span>{{ ad.like_count }}</span>
            </div>
            <div class="stat-item">
              <el-icon><SvgIcon iconName="icon-buxihuan" /></el-icon>
              <span>{{ ad.dislike_count }}</span>
            </div>
          </div>
          <el-button type="primary" @click="openCreativeDialog(ad)" class="detail-button">
            详情
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 创意详情对话框 -->
    <el-dialog v-model="creativeDialogVisible" title="广告创意详情" width="60%">
      <div v-if="selectedAd">
        <h3>{{ selectedAd.name }}</h3>
        <div class="creative-info">
          <p>预算: {{ selectedAd.budget_fee }}</p>
          <div class="ad-stats">
            <!-- 点击量 -->
            <div class="stat-item">
              <el-icon><SvgIcon iconName="icon-dianji" /></el-icon>
              <span>{{ selectedAd.click_count }}</span>
            </div>
            <!-- 点赞量 -->
            <div class="stat-item">
              <el-icon><SvgIcon iconName="icon-xihuan" /></el-icon>
              <span>{{ selectedAd.like_count }}</span>
            </div>
            <div class="stat-item">
              <el-icon><SvgIcon iconName="icon-buxihuan" /></el-icon>
              <span>{{ selectedAd.dislike_count }}</span>
            </div>
          </div>
          <p>兴趣标签:
            <el-tag v-for="hobby in selectedAd.hobbies" :key="hobby" size="small" style="margin-right: 5px;">{{ hobby }}</el-tag>
          </p>
          <p>地域标签:
            <el-tag v-for="district in selectedAd.districts" :key="district" size="small" style="margin-right: 5px;">{{ district }}</el-tag>
          </p>
        </div>
        <div class="creative-detail">
          <div v-if="selectedAd.creatives?.length">
            <!-- 当前创意展示 -->
            <h4>{{ selectedAd.creatives[currentCreativeIndex].name }}</h4>
            <el-image
                v-if="selectedAd.creatives[currentCreativeIndex].creative_type === '图片'"
                :src="getFullUrl(selectedAd.creatives[currentCreativeIndex].url)"
                fit="contain"
                style="width: 100%; max-height: 500px;"
            />
            <video
                v-if="selectedAd.creatives[currentCreativeIndex].creative_type === '视频'"
                :src="getFullUrl(selectedAd.creatives[currentCreativeIndex].url)"
                controls
                style="width: 100%; max-height: 500px;"
            />
          </div>
          <!-- 创意切换 -->
          <div class="creative-thumbnails">
            <div
                v-for="(creative, index) in selectedAd.creatives"
                :key="creative.creative_id"
                class="thumbnail-item"
                :class="{ active: currentCreativeIndex === index }"
                @click="switchCreative(index)"
            >
              <el-image
                  v-if="creative.creative_type === '图片'"
                  :src="getFullUrl(creative.url)"
                  fit="cover"
                  style="width: 80px; height: 60px;"
              />
              <video
                  v-if="creative.creative_type === '视频'"
                  :src="getFullUrl(creative.url)"
                  style="width: 80px; height: 60px;"
              />
            </div>
          </div>
        </div>
        <el-button type="primary" @click="openFeedbackDialog">
          <el-icon><Star /></el-icon> 反馈
        </el-button>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="creativeDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 反馈对话框 -->
    <el-dialog v-model="feedbackDialogVisible" title="用户反馈" width="40%" @close="resetFeedback">
      <el-form :model="feedbackForm" label-width="120px">
        <el-form-item label="广告名称">
          <span>{{ selectedAd.name }}</span>
        </el-form-item>
        <el-form-item label="反馈类型">
          <el-radio-group v-model="feedbackForm.feedback">
            <el-radio label="like">
              <el-icon><SvgIcon iconName="icon-xihuan" /></el-icon> 喜欢
            </el-radio>
            <el-radio label="dislike">
              <el-icon><SvgIcon iconName="icon-buxihuan" /></el-icon> 不喜欢
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="反馈意见">
          <el-input v-model="feedbackForm.comment" type="textarea" placeholder="请填写您的反馈意见" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeFeedbackDialog">取消</el-button>
          <el-button type="primary" @click="submitFeedback">提交反馈</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.ad-display-container {
  padding: 20px;
}

.top-ad-card {
  text-align: center;
  position: relative;
}

.detail-button {
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.ads-list {
  margin-top: 20px;
}

.ad-card {
  margin-bottom: 20px;
  position: relative;
}

.ad-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.creative-info {
  margin-bottom: 20px;
  p {
    margin: 5px 0;
  }
}

.creative-detail {
  text-align: center;
}

.creative-thumbnails {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 10px;
}

.thumbnail-item {
  cursor: pointer;
  border: 2px solid transparent;
  &.active {
    border-color: #409eff;
  }
}

.search-bar {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.ad-stats {
  display: flex;
  gap: 15px;
  margin: 10px 0;
  .stat-item {
    display: flex;
    align-items: center;
    .stat-icon {
      width: 18px;
      height: 18px;
      margin-right: 5px;
    }
    span {
      font-size: 14px;
      color: #666;
    }
  }
}
</style>